package com.yehun.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.yehun.dao.RoleDao;
import com.yehun.dao.UserDao;
import com.yehun.entity.PagerEntity;
import com.yehun.entity.Role;
import com.yehun.entity.User;
import com.yehun.exception.ErrorException;
import com.yehun.service.RoleService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {

    @Resource
    private RoleDao roleDao;

    @Resource
    private UserDao userDao;

    @Override
    public List<Role> listAll() {
        return roleDao.listAll();
    }

    @Override
    public PagerEntity<Role> listPager(int pageIndex, int pageSize) {
        PagerEntity<Role> pager = new PagerEntity<>();
        Page page = PageHelper.startPage(pageIndex, pageSize);
        pager.setData(roleDao.listAll());
        pager.setTotal(page.getTotal());
        pager.setPageIndex(pageIndex);
        pager.setPageSize(pageSize);
        return pager;
    }

    @Override
    public Role get(int id) {
        return roleDao.get(id);
    }

    @Override
    public int save(Role role) {
        return roleDao.save(role);
    }

    @Override
    public int update(Role role) {
        return roleDao.update(role);
    }

    @Override
    public int updateUserNumber(int id) {
        return roleDao.updateUserNumber(id);
    }

    @Override
    public int updatePermission(int id, long permission) {
        return roleDao.updatePermission(id, permission);
    }

    @Override
    public int remove(Integer[] idArray) throws ErrorException {
        if (idArray == null || idArray.length <= 0) {
            throw new ErrorException("用户id不能为空");
        }
        Role roleTmp;
        for (Integer id : idArray) {
            roleTmp = roleDao.get(id);
            if (roleTmp == null) {
                throw new ErrorException(String.format("角色[%d]不存在", id));
            }
            List<User> users = userDao.listByRoleId(id);
            if (users != null && !users.isEmpty()) {
                throw new ErrorException(String.format("ID为[%d]的角色[%s]存在%d个用户,不允许删除,如需删除,请先清空角色的用户再尝试!", id, roleTmp.getName(), users.size()));
            }
        }
        return roleDao.remove(idArray);
    }
}
